# coding: utf-8
import os
import sys
import logging
import pygame

try:
    __file__
except NameError as e:
    from whereis import mymain
    rootdir = mymain()
else:
    rootdir = os.path.dirname(os.path.dirname(__file__))

sys.path.insert(0, rootdir)
from lib.bashlog import getlogger
from lib.tracemore import get_exc_plus
from lib.config import Config
from lib.data import Data
from lib import color
from lib import events
from lib.mainpage import MainPage
from lib.scrollpage import LanguagePage
from lib.scrollpage import CategoryPage
from lib.scrollpage import LibPage
from lib.gamepage import GamePage
from lib.modepage import ModePage
sys.path.pop(0)

logger = logging.getLogger('wordson.game')

cfg = Config()
data = Data()

class Game(object):
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode(cfg.screen)

        self.main_page = MainPage()
        self.lang_page = LanguagePage(data.get_langs())
        self.mode_page = ModePage()
        self.load_page = None
        self.game_page = GamePage()

        self.current_page = self.main_page

        self.running = True

    def cache_cate(func):
        cached = {}
        def warpper(self):
            return cached.setdefault(cfg.lang, func(self))
        return warpper
    @property
    @cache_cate
    def cate_page(self):
        return CategoryPage(data.get_cates_under(cfg.lang))


    def cache_lib(func):
        cached = {}
        def warpper(self):
            return cached.setdefault((cfg.lang, cfg.cate), func(self))
        return warpper

    @property
    @cache_lib
    def page_lib(self):
        result = data.get_name_path_under(cfg.lang, cfg.cate)
        return LibPage(map(lambda x: x[0], result))


    def run(self):

        pygame.key.set_repeat(cfg.key_repeat_delay, cfg.key_repeat_interval)
        pygame.display.set_caption(cfg.title)

        screen = self.screen

        clock = pygame.time.Clock()

        while self.running:
            for event in pygame.event.get():
                if self.current_page.handle(event):
                    continue
                if self.handle(event):
                    continue


            interval = clock.tick(cfg.tick)
            self.current_page.update(interval)
            screen.fill(color.white)
            self.current_page.draw(screen)
            pygame.display.flip()

        pygame.quit()

    def handle(self, event):
        if event.type == pygame.QUIT:
            logger.info('exit...')
            self.running = False
            return True
        if event.type == events.SWITCHPAGE:
            to = event.to
            logger.debug('switch page %s', event)
            if to == cfg.page_main:
                logger.info('to main page')
                self.current_page = self.main_page
                # if hasattr(self, 'lang'):
                #     del self.lang
            elif to == cfg.page_lang:
                logger.info('to language page')
                self.current_page = self.lang_page
                if hasattr(cfg, 'lang'):
                    del cfg.lang
            elif to == cfg.page_cate:
                logger.info('to category page')
                if event.by == cfg.page_lang:
                    cfg.lang = event.lang
                self.current_page = self.cate_page
            elif to == cfg.page_lib:
                logger.info('to lib page')
                if event.by == cfg.page_cate:
                    cfg.cate = event.cate
                self.current_page = self.page_lib
            elif to == cfg.page_mode:
                logger.info('to mode page')
                if event.by == cfg.page_lib:
                    cfg.lib = event.lib
                self.current_page = self.mode_page
            elif to == cfg.page_load:
                self.current_page = self.load_page
            elif to == cfg.page_game:
                logger.info('to game page')

                cfg.show_type = event.show_type
                cfg.repeat_word = event.repeat

                cfg.write_word = event.write_word
                cfg.choose_word = event.choose_word
                cfg.choose_meaning = event.choose_meaning
                lang = cfg.lang
                cate = cfg.cate
                logger.debug('switch to game %s - %s', lang, cate)
                self.current_page = self.game_page
            logger.debug('event %s handle by game', event)
            return True

def main():
    return Game().run()

if __name__ == '__main__':
    getlogger('wordson', logging.DEBUG)
    main()
